﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Note_CHUSHI
{
    public static class AIService
    {
        // 文本生成API配置
        private const string TextApiKey = "6yQexMANmyQVZWkv99lKtYJi";
        private const string TextSecretKey = "arUCtKtyCJTSmWcuZhgPJlsE4MXbIsll";
        private const string TextApiUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
     
        private static async Task<string> GetAccessToken(string apiKey, string secretKey)
        {
            using (var client = new HttpClient())
            {
                var url = $"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={apiKey}&client_secret={secretKey}";
                var response = await client.GetAsync(url);
                var content = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<dynamic>(content);
                return result.access_token;
            }
        }

        // 生成AI文本
        public static async Task<string> GenerateText(string prompt)
        {
            try
            {
                var accessToken = await GetAccessToken(TextApiKey, TextSecretKey);
                using (var client = new HttpClient())
                {
                    var url = $"{TextApiUrl}?access_token={accessToken}";
                    var requestData = new
                    {
                        messages = new[]
                        {
                            new
                            {
                                role = "user",
                                content = prompt
                            }
                        }
                    };

                    var content = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(url, content);
                    var result = await response.Content.ReadAsStringAsync();
                    var json = JsonConvert.DeserializeObject<dynamic>(result);
                    return json.result;
                }
            }
            catch (Exception ex)
            {
                return $"AI文本生成失败: {ex.Message}";
            }
        }
    }
}
